package com.cofiroute.ldap;

import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.userdetails.UserDetails;


public class AuthenticationProviderCofiLdap extends AbstractUserDetailsAuthenticationProvider {
    
  private static final Logger log = Logger.getLogger(AuthenticationProviderCofiLdap.class);
  
  private CofiDetailsService userDetailsService;

  /**
  * Setter injection.
  * @param userDetailsService
  */
  public void setUserDetailsService(CofiDetailsService dao) {
    this.userDetailsService = dao;
  }
  
  
  protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) {
  }
  
  protected final UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) {
    UserDetails lclsUserDetails;
    
    try {
      String  lsPassword = (String)authentication.getCredentials();
      //System.out.println("Tentative de recuperation des donnees utilisateur avec le mot de passe saisi : " + lsPassword);    
      lclsUserDetails =  (UserDetails) userDetailsService.loadUserByUsername(username, lsPassword);
    }
    catch (DataAccessException repositoryProblem) {
      throw new AuthenticationServiceException(repositoryProblem.getMessage(), repositoryProblem);
    }
    
    if (lclsUserDetails == null) {
      throw new AuthenticationServiceException("AuthenticationDao returned null, which is an interface contract violation");
    }
    
    log.debug(lclsUserDetails.toString());
    
    return lclsUserDetails;
  }
}

